package com.apesource.project02.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apesource.project02.config.ElasticSearchConfig;
import com.apesource.project02.mapper.IMessagesMapper;
import com.apesource.project02.pojo.Message;
import com.apesource.project02.util.ResponseEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @auther:暮雪
 * @date:2025/9/18
 */

@Service
public class MessageServiceImp extends ServiceImpl<IMessagesMapper, Message> implements IMessageService {

    @Autowired
    private RedisTemplate jsonRedisTemplate;
    @Autowired
    private IMessagesMapper messagesMapper;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public ResponseEntity<List<Message>> getAllMessages(int userId) {
        ResponseEntity<List<Message>> messageResponseEntity = new ResponseEntity<>();
        Set<String> keys = jsonRedisTemplate.keys("message:id:*");
        List<Message> messageList = new ArrayList<>();
        Message message = new Message();
        if (keys.size() > 0) {
            for (String key : keys) {
                Object jsonObj = jsonRedisTemplate.opsForValue().get(key);
                if (jsonObj != null) message = JSON.parseObject(jsonObj.toString(), Message.class);
                messageList.add(message);
            }
        } else {

            messageList = messagesMapper.selectList(null);
            for (Message m : messageList) {
                if (m != null)
                    jsonRedisTemplate.opsForValue().set("message:id:" + m.getMessageId(), JSON.toJSONString(m));
            }
        }
        messageResponseEntity.setData(messageList.stream().filter(message1 -> message1.getUserId() == userId).collect(Collectors.toList()));
        messageResponseEntity.setStatusCode(200);
        messageResponseEntity.setMessage("success");
        return messageResponseEntity;
    }


    @Override
    public ResponseEntity<List<Message>> getMessageByKeyWord(String keyword) {
        ResponseEntity<List<Message>> messageResponseEntity = new ResponseEntity<>();
        try {
            //判断索引库是否存在？
            //1.创建request请求
            GetIndexRequest getIndexRequest= new GetIndexRequest("message");
            //2.发送请求
            boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            if (!exists) {
                //1.创建Request对象
                CreateIndexRequest createIndexRequest= new CreateIndexRequest("message");
                //2.准备请求的参数：DSL语句
                createIndexRequest.source(ElasticSearchConfig.MAPPING_TEMPLATE, XContentType.JSON);
                //3.发送请求
                client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

                //在索引库中添加数据
                List<Message> messageList = messagesMapper.selectList(null);

                //1.创建Request
                BulkRequest bulkRequest = new BulkRequest();
                for (Message m : messageList) {
                    bulkRequest.add(new IndexRequest("message").id(String.valueOf(m.getMessageId())).source(JSON.toJSONString(m), XContentType.JSON));
                }
                //2.发送请求
                client.bulk(bulkRequest, RequestOptions.DEFAULT);
            }

            //搜索功能
            SearchRequest searchRequest= new SearchRequest("message");
//            searchRequest.source().query(QueryBuilders.matchQuery("content", keyword));
            searchRequest.source().query(QueryBuilders.matchAllQuery());
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            long total = searchHits.getTotalHits().value;
            System.err.println("共搜索到" + total + "条数据");
            // 4.2.文档数组
            SearchHit[] hits = searchHits.getHits();
            // 4.3.遍历
            List<Message> messageList = new ArrayList<>();
            for (SearchHit hit : hits) {
                // 获取文档source
                String json = hit.getSourceAsString();
                // 反序列化
                Message message = JSON.parseObject(json, Message.class);
                messageList.add(message);
            }
            messageResponseEntity.setData(messageList);
            messageResponseEntity.setStatusCode(200);
            messageResponseEntity.setMessage("success");
            return messageResponseEntity;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
